/*
 * @Author: yangrongxin
 * @Date: 2021-04-13 16:09:22
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:30:29
 */
import 'reflect-metadata';
import hxRequest from '@/utils/request';
import RequestUtilsBase from './utils';
import './request';

// 注入模块代码 未来进行抽离
import Modules from './modules';

/**
 * @description 当前的请求实例 继承工具类是为了获取对应的请求方法
 * @author yangrongxin
 * @date 2021-04-13
 * @class RequestInstance
 * @extends {RequestUtilsBase}
 */
class RequestInstance extends RequestUtilsBase {
  static instance: any;
  static requestMethod = hxRequest; // 存储当前的请求方式

  /**
   * @description 获取当前请求对象的单例
   * @author yangrongxin
   * @date 2021-04-13
   * @memberof RequestInstance
   */
  public getInstance() {
    if (RequestInstance.instance) {
      return RequestInstance.instance;
    }
    RequestInstance.instance = new RequestInstance();
    return RequestInstance.instance;
  }

  static request(
    api: string,
    data: any = {},
    config: any = {
      showOriginData: true,
    },
  ) {
    const { url, method } = super.toObject(api);
    return RequestInstance.requestMethod(url, {
      method,
      data,
      ...config,
    });
  }

  /**
   * @description
   * @author yangrongxin
   * @date 2021-04-13
   * @static
   * @memberof RequestInstance
   */
  setup(modules: any) {
    // 增加禁止注入的关键字
    const KEYWORD = Reflect.ownKeys(RequestInstance);
    Object.entries(modules).forEach(([k, v]) => {
      if (KEYWORD.indexOf(k) === -1) {
        RequestUtilsBase[k] = v;
        RequestUtilsBase[v.name] = v;
        this[k] = v;
        // TODO: 进行类方法对象的注入
        this[v.name] = v;
      } else {
        console.warn(`存在关键字：${k}，对应模块安装失败`);
      }
    });
  }
}

const Request = new RequestInstance().getInstance();

export default RequestInstance.request;

Request.setup(Modules);

export { Request, RequestUtilsBase };
